# app/services/auth_service.py
from app import db
from app.models import User, GuestUser, Channel, ServerMember, ChannelPermission, File, Friend
from app.utils.security import hash_password, verify_password
from datetime import datetime, timedelta
import uuid
from app.utils.response_utils import (
    success_response,
    error_response,
    ResponseCode
)


class AuthService:
    @staticmethod
    def register_user(username, password, email=None):
        """注册新用户"""

        user = User.query.filter_by(email=email).first()

        if user:
            return '邮箱已被注册',401

        try:
            # 创建新用户
            user_id = str(uuid.uuid4())
            new_user = User(
                user_id=user_id,
                username=username,
                email=email,
                password_hash=hash_password(password),
                is_registered=True,
                actServer='server_default'
            )

            db.session.add(new_user)
            db.session.flush()  # 确保用户ID在数据库中生成

            # 创建服务器成员
            membership_id = AuthService.create_server_member(user_id=user_id)

            # 创建频道权限
            AuthService.create_channel_permissions(membership_id,'user')

            db.session.commit()
            return new_user, 200
        except Exception as e:
            db.session.rollback()
            return f'注册失败: {str(e)}', 500

    @staticmethod
    def authenticate_user(email, password):
        """验证用户凭据"""
        user = User.query.filter_by(email=email).first()
        if user and verify_password(user.password_hash, password):
            return user
        return None

    @staticmethod
    def create_guest():
        """创建临时访客"""
        try:
            guest_id = str(uuid.uuid4())
            session_token = str(uuid.uuid4())
            expires_at = datetime.utcnow() + timedelta(days=1)

            new_guest = GuestUser(
                guest_id=guest_id,
                session_token=session_token,
                expires_at=expires_at,
                actServer='server_default'
            )

            db.session.add(new_guest)
            db.session.flush()  # 确保游客ID在数据库中生成

            # 创建服务器成员
            membership_id = AuthService.create_server_member(guest_id=guest_id)

            # 创建频道权限
            AuthService.create_channel_permissions(membership_id,'guest')

            db.session.commit()
            return new_guest
        except Exception as e:
            db.session.rollback()
            return f'创建游客失败: {str(e)}', 500

    @staticmethod
    def get_default_server_channels():
        """获取默认服务器的所有频道"""
        return Channel.query.filter_by(server_id='server_default').all()

    @staticmethod
    def create_server_member(user_id=None, guest_id=None):
        """创建服务器成员记录"""
        membership_id = str(uuid.uuid4())

        # 使用第一个文本频道作为活跃频道
        text_channel = Channel.query.filter_by(
            server_id='server_default',
            type='text'
        ).order_by('position').first()

        act_channel = str(text_channel.channel_id) if text_channel else None

        # 确定角色
        role = 'member' if user_id else None

        member = ServerMember(
            membership_id=membership_id,
            server_id='server_default',
            user_id=user_id,
            guest_id=guest_id,
            actChannel=act_channel,
            role='member' if user_id else None,
            can_leave=False
        )

        db.session.add(member)
        return membership_id

    @staticmethod
    def create_channel_permissions(member_id, userType):
        """为成员创建默认频道权限"""
        channels = AuthService.get_default_server_channels()

        for channel in channels:
            permission = ChannelPermission(
                permission_id=str(uuid.uuid4()),
                channel_id=channel.channel_id,
                member_id=member_id,
                can_view=True,
                can_send=True,  # 文本频道可发送消息
                can_connect=(userType == 'user')  # 语音频道可连接
            )
            db.session.add(permission)

    @staticmethod
    def get_personal_info(user_id:str):

        user = User.query.filter_by(user_id=user_id).first()
        serverCount = ServerMember.query.filter_by(user_id=user_id).count()
        fileCount = File.query.filter_by(uploader_id=user_id).count()
        friendCount = Friend.query.filter_by(user_id=user_id).count()
        avatar_file = File.query.filter_by(file_url=user.avatar_url).first()

        if avatar_file:
            result = {
                'user_id': user.user_id,
                'username': user.username,
                'email': user.email,
                'avatar_id': avatar_file.file_id,
                'avatar_url': user.avatar_url,
                'status': user.status,
                'created_at': user.created_at,
                'serverCount': serverCount,
                'fileCount': fileCount,
                'friendCount': friendCount,
                'bio': user.bio,
                'tags': user.tags
            }
        else:
            result = {
                'user_id': user.user_id,
                'username': user.username,
                'email': user.email,
                'avatar_url': user.avatar_url,
                'status': user.status,
                'created_at': user.created_at,
                'serverCount': serverCount,
                'fileCount': fileCount,
                'friendCount': friendCount,
                'bio': user.bio,
                'tags': user.tags
            }

        return result

    @staticmethod
    def edit_userInfo(user_id:str,username:str,email:str,bio:str,avatar_url:str,tags:str):
        user = User.query.filter_by(user_id=user_id).first()
        if username:
            user.username = username

        if email:
            user.email = email

        user.bio = bio

        if avatar_url:
            user.avatar_url = avatar_url

        if tags:
            user.tags = tags

        db.session.commit()
        return '修改成功'